package com.cjxt.ams.controller;


import com.cjxt.ams.dao.UserDao;
import com.cjxt.ams.domain.User;
import com.cjxt.ams.service.UserLoginService;
import com.cjxt.ams.service.impl.UserLoginServiceImpl;
import com.cjxt.ams.shiro.ShiroUtils;

import com.cjxt.ams.utils.MD5Utils;
import com.cjxt.ams.utils.Result;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author XueYunFei
 * @version V1.0
 * @Description: 登录
 * @className: UserController
 * @date 2021/11/22 10:20
 * @company:华勤技术股份有限公司
 * @copyright: Copyright (c) 2021
 */


@Controller
@RequestMapping("/ams")
public class UserLoginController extends AbstractController {

    @Autowired
    private Producer producer;

    @Autowired
    private UserLoginService loginService;

    @Autowired
    private UserDao userDao;


    private static String str = "123456";

    //记录用户账号
    private String tempAccount;

    public static int errorCount;


    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    /**
     * @description: 登录发起的get请求
     * @author XueYunFei
     * @date 2021/11/30 9:39
     */

    @GetMapping("/loginIndex")
    public String login(Model model) {
        User user = new User();
        model.addAttribute(user);
        return "user/login";
    }

    /**
     * @param useraccount 账号
     * @param password    密码
     * @param captcha     验证码
     * @return Result
     * @description: 登录发起的post请求
     * @author XueYunFei
     * @date 2021/11/30 9:40
     */

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestParam("useraccount") String useraccount, @RequestParam("password") String password, String captcha) {
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        MD5Utils utils = new MD5Utils();
        String pass = utils.string2MD5(password);

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        User user = userDao.selectOne(new QueryWrapper<User>().eq("useraccount",useraccount));

        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return Result.error("验证码不正确");
        }

        //判断账户是否被锁定
        boolean be = loginService.judegLock(useraccount);


        if (be) {
            return Result.error("登录失败次数过多，请" + (30 - UserLoginServiceImpl.minutes) + "分钟后再试！");
        }


        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(useraccount, pass);

            subject.login(token);

            //获取到当前登录用户的账号
            tempAccount = token.getUsername();

        } catch (UnknownAccountException e) {
            return Result.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
//            e.printStackTrace();
            errorCount++;
            if (errorCount >= 3) {
                UserLoginServiceImpl.user.setLockTime(dateFormat.format(date));
                userDao.updateById(UserLoginServiceImpl.user);
                return Result.error("账户已被锁定，请30分钟后再试！");
            }
            return Result.error("账号或者密码错误,还有" + (3 - errorCount) + "次机会！");
        } catch (LockedAccountException e) {
            return Result.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return Result.error("账户验证失败++++++++++++");
        }
        if (password.equals(str)) {
            return Result.error("账户密码为初始密码，请修改密码");
        }


        return Result.ok("登录成功!");
    }


    /**
     * @description: 第一次登录需要修改密码
     * @author XueYunFei
     * @date 2021/11/30 9:41
     */

    @GetMapping("/updatePassword")
    public String updatePassword() {
        return "user/password";
    }


    /**
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @description: 修改登录用户密码
     * @author XueYunFei
     * @date 2021/12/17 17:23
     */

    @ResponseBody
    @PostMapping("/password")
    public Result password(String oldPassword, String newPassword) {

        //判断密码是否包含字母
        boolean booPass = loginService.judgeContainsStr(newPassword);

        if (oldPassword.length() <= 0) {
            return Result.error("原密码不能为空");
        }

        if (newPassword.length()<=0){
            return Result.error("新密码不能为空");
        }

        if (!booPass) {
            return Result.error("新密码必须包含字符");
        }

        if (newPassword.length() < 6 || newPassword.length() > 12) {
            return Result.error("长度不能小于6位,大于12位");
        }


        //更新密码
        boolean flag = loginService.updatePassword(tempAccount, oldPassword, newPassword);

        if (!flag) {
            return Result.error("原密码不正确");
        }


        return Result.ok("修改成功");
    }


    /**
     * @param model
     * @description: 登录成功跳转到欢迎页面
     * @author XueYunFei
     * @date 2021/11/30 9:38
     */

    @GetMapping("/welcome")
    public String show(Model model) {
        User user = new User();
        model.addAttribute(user);
        return "welcome/index";
    }

    /**
     * 退出
     */
    @GetMapping("/logout")
    public String logout(Model model) {
        ShiroUtils.logout();
        return "redirect:/user/login";
    }


}
